package com.tianji.remark.task;

import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.StringUtils;
import com.tianji.remark.service.impl.LikedRecordServiceImpl2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class SyncRedisToMysql {

    private static final String[] BIZ_TYPES = new String[]{"QA", "NOTE"};

    @Autowired
    private LikedRecordServiceImpl2 recordService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitMqHelper mqHelper;

    @Scheduled(fixedRate = 30, timeUnit = TimeUnit.SECONDS)
    public void syncRedisToMysql(){
        log.info("syncRedisToMysql start。。。");
        // 读入redis的zset中的点赞次数
        // 遍历所有的业务类型
        for (String bizType : BIZ_TYPES) {
            log.info("bizType：{}", bizType);
            String key = recordService.likeTimesKey(bizType);
            while(true){
                // 从redis中读取最多10条记录
                Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().popMax(key, 10);
                if(CollectionUtils.isEmpty(typedTuples)){
                    break;
                }
                // 把redis中的数据转化消息DTO
                List<LikedTimesDTO> msgList = new ArrayList<>();
                for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
                    String bizId = typedTuple.getValue();
                    Double likedTimes = typedTuple.getScore();
                    LikedTimesDTO dto = new LikedTimesDTO();
                    dto.setBizId(Long.parseLong(bizId));
                    dto.setLikedTimes(likedTimes.intValue());
                    msgList.add(dto);
                }
                // 发送消息
                String routingKey = StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, bizType);
                mqHelper.send(MqConstants.Exchange.LIKE_RECORD_EXCHANGE, routingKey, msgList);
            }
        }
        log.info("syncRedisToMysql end");
    }
}
